using System;
using System.Xml;

namespace BasecampRestAPI
{
	public class Milestone : IMilestone
	{
		private readonly IBaseCamp _camp;
		private readonly int _responsiblePartyId;
		private IPerson _responsibleParty;
		private readonly int _creatorId;
		private IPerson _creator;
		private readonly int _projectId;
		private IProject _project;

		public static IMilestone GetInstance(IBaseCamp camp, XmlNode node)
		{
			return new Milestone(camp, node);
		}
		private Milestone(IBaseCamp camp, XmlNode node)
		{
			_camp = camp;
			Id = XmlHelpers.ParseInteger(node, "id");
			Title = XmlHelpers.ChildNodeText(node, "title");
			CreatedOn = XmlHelpers.ParseDateTime(node, "created-on");
			Deadline = XmlHelpers.ParseDateTime(node, "deadline", CreatedOn);
			Title = XmlHelpers.ChildNodeText(node, "title");
			WantsNotification = XmlHelpers.ParseBool(node, "wants-notification");
			_responsiblePartyId = XmlHelpers.ParseInteger(node, "responsible-party-id");
			Completed = XmlHelpers.ParseBool(node, "completed");
			_creatorId = XmlHelpers.ParseInteger(node, "creator-id");
			_projectId = XmlHelpers.ParseInteger(node, "project-id");
		}

		#region Implementation of IMilestone

		public int Id { get; private set; }
		public bool Completed { get; private set; }
		public DateTime CreatedOn { get; private set; }
		public DateTime Deadline { get; set; }
		public string Title { get; set; }
		public bool WantsNotification { get; private set; }
		public IPerson ResponsibleParty
		{
			get
			{
				if (_responsibleParty == null)
				{
					_responsibleParty = _camp.GetPersonById(_responsiblePartyId);
				}
				return _responsibleParty;
			}
		}
		public IPerson Creator
		{
			get
			{
				if (_creator == null)
				{
					_creator = _camp.GetPersonById(_creatorId);
				}
				return _creator;
			}
		}
		public IProject Project
		{
			get
			{
				if (_project == null)
				{
					_project = _camp.GetProjectById(_projectId);
				}
				return _project;
			}
		}

		#endregion
	}
}
